import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
  CallToolRequestSchema,
  ListResourcesRequestSchema,
  ListToolsRequestSchema,
  ReadResourceRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';

// Database and Cache imports
import { DatabaseManager } from '../database/DatabaseManager.js';
import { RedisClient, CacheManager } from '../cache/index.js';
import { ComponentRegistryFactory } from '../components/ComponentRegistryFactory.js';
import type { IComponentRegistry } from '../components/ComponentRegistryFactory.js';
import { CodeGenerator } from '../components/CodeGenerator.js';
import { TemplateEngine } from '../templates/TemplateEngine.js';
import { DocumentSearcher } from '../docs/DocumentSearcher.js';
import { PerformanceMonitor, HealthChecker } from '../monitoring/index.js';
import { LoggingService } from '../logging/index.js';

import type { 
  GenerateCodeParams, 
  SearchComponentsParams, 
  GetDocumentationParams,
  ComponentInfo,
  TemplateInfo
} from '../types/index.js';

/**
 * 数据库版本的 MCP Ant Design Server
 * 支持数据库存储和三层缓存
 */
export class DatabaseMCPServer {
  private server: Server;
  private dbManager: DatabaseManager;
  private cacheManager?: CacheManager;
  private componentRegistry!: IComponentRegistry;
  private codeGenerator: CodeGenerator;
  private templateEngine: TemplateEngine;
  private documentSearcher: DocumentSearcher;
  private performanceMonitor!: PerformanceMonitor;
  private healthChecker!: HealthChecker;
  private loggingService!: LoggingService;
  
  private initialized = false;

  constructor() {
    this.server = new Server(
      {
        name: 'mcp-server-antd-database',
        version: '1.0.0',
      },
      {
        capabilities: {
          resources: {},
          tools: {},
        },
      }
    );

    this.dbManager = new DatabaseManager();
    this.codeGenerator = new CodeGenerator();
    this.templateEngine = new TemplateEngine();
    this.documentSearcher = new DocumentSearcher();
  }

  /**
   * 初始化服务器 - 数据库、缓存、组件注册表
   */
  async initialize(): Promise<void> {
    if (this.initialized) return;

    try {
      console.log('🚀 初始化 MCP Server Database 版本...');
      
      // 1. 初始化数据库
      await this.dbManager.initialize();
      console.log('✅ 数据库初始化完成');

      // 2. 初始化缓存系统
      await this.initializeCache();

      // 3. 初始化组件注册表
      await this.initializeComponentRegistry();

      // 4. 初始化监控系统
      await this.initializeMonitoring();

      // 5. 初始化日志系统
      await this.initializeLogging();

      // 6. 设置请求处理器
      this.setupHandlers();

      this.initialized = true;
      console.log('🎉 MCP Server Database 版本初始化完成');
    } catch (error) {
      console.error('❌ MCP Server 初始化失败:', error);
      throw error;
    }
  }

  /**
   * 初始化缓存系统
   */
  private async initializeCache(): Promise<void> {
    try {
      await RedisClient.connect();
      this.cacheManager = CacheManager.getInstance(RedisClient, this.dbManager.getConnection());
      console.log('✅ 缓存系统初始化完成');
    } catch (error) {
      console.warn('⚠️  缓存系统初始化失败，将以仅数据库模式运行:', error);
      this.cacheManager = undefined;
    }
  }

  /**
   * 初始化组件注册表
   */
  private async initializeComponentRegistry(): Promise<void> {
    try {
      this.componentRegistry = await ComponentRegistryFactory.getAdaptiveRegistry(
        this.dbManager.getRepositories(),
        this.cacheManager
      );
      console.log(`✅ 组件注册表初始化完成 (${this.componentRegistry.isDatabaseBacked?.() ? '数据库' : '内存'}模式)`);
    } catch (error) {
      console.error('❌ 组件注册表初始化失败:', error);
      throw error;
    }
  }

  /**
   * 初始化监控系统
   */
  private async initializeMonitoring(): Promise<void> {
    try {
      // 初始化性能监控
      this.performanceMonitor = PerformanceMonitor.getInstance(this.dbManager.getRepositories());
      console.log('✅ 性能监控初始化完成');
      
      // 初始化健康检查
      this.healthChecker = HealthChecker.getInstance(
        this.dbManager,
        this.dbManager.getRepositories()
      );
      console.log('✅ 健康检查初始化完成');
    } catch (error) {
      console.error('❌ 监控系统初始化失败:', error);
      throw error;
    }
  }

  /**
   * 初始化日志系统
   */
  private async initializeLogging(): Promise<void> {
    try {
      // 初始化日志服务
      this.loggingService = LoggingService.getInstance(this.dbManager.getRepositories());
      
      // 生成会话 ID
      const sessionId = this.loggingService.generateSessionId();
      console.log(`✅ 日志系统初始化完成 (Session: ${sessionId.substring(0, 8)}...)`);
    } catch (error) {
      console.error('❌ 日志系统初始化失败:', error);
      throw error;
    }
  }

  private setupHandlers(): void {
    // List available tools
    this.server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: 'generate_antd_code',
            description: '生成 Ant Design 组件代码',
            inputSchema: {
              type: 'object',
              properties: {
                component: {
                  type: 'string',
                  description: '组件名称 (如: Button, Table, Form)',
                },
                props: {
                  type: 'object',
                  description: '组件属性',
                },
                template: {
                  type: 'string',
                  description: '模板类型',
                },
                framework: {
                  type: 'string',
                  enum: ['react', 'vue', 'angular'],
                  description: '前端框架',
                  default: 'react',
                },
                includeImports: {
                  type: 'boolean',
                  description: '是否包含导入语句',
                  default: true,
                },
                includeStyles: {
                  type: 'boolean',
                  description: '是否包含样式',
                  default: false,
                },
              },
              required: ['component'],
            },
          },
          {
            name: 'search_antd_components',
            description: '搜索 Ant Design 组件',
            inputSchema: {
              type: 'object',
              properties: {
                query: {
                  type: 'string',
                  description: '搜索查询',
                },
                category: {
                  type: 'string',
                  description: '组件分类',
                },
                limit: {
                  type: 'number',
                  description: '结果数量限制',
                  default: 10,
                },
              },
              required: ['query'],
            },
          },
          {
            name: 'get_antd_documentation',
            description: '获取 Ant Design 组件文档',
            inputSchema: {
              type: 'object',
              properties: {
                component: {
                  type: 'string',
                  description: '组件名称',
                },
                version: {
                  type: 'string',
                  description: 'Ant Design 版本',
                },
                language: {
                  type: 'string',
                  enum: ['zh', 'en'],
                  description: '文档语言',
                  default: 'zh',
                },
              },
              required: ['component'],
            },
          },
          {
            name: 'list_antd_templates',
            description: '列出可用的 Ant Design 模板',
            inputSchema: {
              type: 'object',
              properties: {
                category: {
                  type: 'string',
                  description: '模板分类',
                },
                framework: {
                  type: 'string',
                  enum: ['react', 'vue', 'angular'],
                  description: '前端框架',
                },
              },
            },
          },
          {
            name: 'get_popular_components',
            description: '获取热门组件',
            inputSchema: {
              type: 'object',
              properties: {
                limit: {
                  type: 'number',
                  description: '返回数量',
                  default: 10,
                },
              },
            },
          },
          {
            name: 'get_server_stats',
            description: '获取服务器统计信息',
            inputSchema: {
              type: 'object',
              properties: {},
            },
          },
          {
            name: 'get_health_status',
            description: '获取系统健康状态',
            inputSchema: {
              type: 'object',
              properties: {},
            },
          },
          {
            name: 'get_performance_report',
            description: '获取性能监控报告',
            inputSchema: {
              type: 'object',
              properties: {
                timeRange: {
                  type: 'string',
                  description: '时间范围 (1h, 24h, 7d)',
                  default: '24h',
                },
              },
            },
          },
          {
            name: 'get_usage_analytics',
            description: '获取使用统计分析',
            inputSchema: {
              type: 'object',
              properties: {
                timeRange: {
                  type: 'string',
                  description: '时间范围 (1h, 24h, 7d, 30d)',
                  default: '24h',
                },
              },
            },
          },
          {
            name: 'get_daily_report',
            description: '获取每日使用报告',
            inputSchema: {
              type: 'object',
              properties: {
                date: {
                  type: 'string',
                  description: '日期 (YYYY-MM-DD)，默认今天',
                },
              },
            },
          },
          {
            name: 'get_recent_logs',
            description: '获取最近的调用日志',
            inputSchema: {
              type: 'object',
              properties: {
                limit: {
                  type: 'number',
                  description: '返回数量',
                  default: 50,
                },
                toolName: {
                  type: 'string',
                  description: '过滤特定工具',
                },
              },
            },
          },
        ],
      };
    });

    // Handle tool calls
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const { name, arguments: args } = request.params;

      try {
        switch (name) {
          case 'generate_antd_code':
            return await this.handleGenerateCode(this.validateGenerateCodeParams(args));
          
          case 'search_antd_components':
            return await this.handleSearchComponents(this.validateSearchComponentsParams(args));
          
          case 'get_antd_documentation':
            return await this.handleGetDocumentation(this.validateGetDocumentationParams(args));
          
          case 'list_antd_templates':
            return await this.handleListTemplates(args || {});

          case 'get_popular_components':
            return await this.handleGetPopularComponents(args || {});

          case 'get_server_stats':
            return await this.handleGetServerStats();

          case 'get_health_status':
            return await this.handleGetHealthStatus();

          case 'get_performance_report':
            return await this.handleGetPerformanceReport(args || {});

          case 'get_usage_analytics':
            return await this.handleGetUsageAnalytics(args || {});

          case 'get_daily_report':
            return await this.handleGetDailyReport(args || {});

          case 'get_recent_logs':
            return await this.handleGetRecentLogs(args || {});
          
          default:
            throw new Error(`Unknown tool: ${name}`);
        }
      } catch (error) {
        console.error(`❌ Tool execution failed [${name}]:`, error);
        return {
          content: [
            {
              type: 'text',
              text: `工具执行失败: ${error instanceof Error ? error.message : String(error)}`,
            },
          ],
          isError: true,
        };
      }
    });

    // List available resources
    this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
      try {
        const components = await this.componentRegistry.getAllComponents();
        const templates = await this.templateEngine.getAllTemplates();

        return {
          resources: [
            ...components.map((comp: ComponentInfo) => ({
              uri: `antd://component/${comp.name}`,
              name: `Ant Design ${comp.name}`,
              description: comp.description,
              mimeType: 'application/json',
            })),
            ...templates.map((template: TemplateInfo) => ({
              uri: `antd://template/${template.name}`,
              name: `Template: ${template.name}`,
              description: template.description,
              mimeType: 'text/plain',
            })),
          ],
        };
      } catch (error) {
        console.error('❌ List resources failed:', error);
        return { resources: [] };
      }
    });

    // Handle resource reads
    this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
      const { uri } = request.params;
      
      try {
        if (uri.startsWith('antd://component/')) {
          const componentName = uri.replace('antd://component/', '');
          const component = await this.componentRegistry.getComponent(componentName);
          
          if (!component) {
            throw new Error(`Component not found: ${componentName}`);
          }
          
          return {
            contents: [
              {
                uri,
                mimeType: 'application/json',
                text: JSON.stringify(component, null, 2),
              },
            ],
          };
        }
        
        if (uri.startsWith('antd://template/')) {
          const templateName = uri.replace('antd://template/', '');
          const template = await this.templateEngine.getTemplate(templateName);
          
          if (!template) {
            throw new Error(`Template not found: ${templateName}`);
          }
          
          return {
            contents: [
              {
                uri,
                mimeType: 'text/plain',
                text: template.template,
              },
            ],
          };
        }
        
        throw new Error(`Unknown resource: ${uri}`);
      } catch (error) {
        console.error(`❌ Read resource failed [${uri}]:`, error);
        throw error;
      }
    });
  }

  private async handleGenerateCode(params: GenerateCodeParams) {
    const perfMeasure = this.performanceMonitor.createMeasure('generate_code', {
      component: params.component,
      framework: params.framework,
    });
    
    const logMeasure = this.loggingService.createMeasure('generate_antd_code', params);
    
    try {
      const code = await this.codeGenerator.generateCode(params);
      
      perfMeasure.end(true, { codeLength: code.length });
      await logMeasure.success({ codeGenerated: true, codeLength: code.length });
      
      return {
        content: [
          {
            type: 'text',
            text: `生成的 ${params.component} 组件代码:\n\n\`\`\`${params.framework || 'react'}\n${code}\n\`\`\``,
          },
        ],
      };
    } catch (error) {
      perfMeasure.end(false, { error: error instanceof Error ? error.message : String(error) });
      await logMeasure.error(error instanceof Error ? error.message : String(error));
      throw error;
    }
  }

  private async handleSearchComponents(params: SearchComponentsParams) {
    const perfMeasure = this.performanceMonitor.createMeasure('search_components', {
      query: params.query,
      category: params.category,
      limit: params.limit,
    });
    
    const logMeasure = this.loggingService.createMeasure('search_antd_components', params);
    
    try {
      const components = await this.componentRegistry.searchComponents(
        params.query,
        params.category,
        params.limit
      );
      
      perfMeasure.end(true, { resultCount: components.length });
      await logMeasure.success({ resultCount: components.length });
      
      const result = components.map((comp: ComponentInfo) => 
        `**${comp.name}** (${comp.category})\n${comp.description}\n`
      ).join('\n');
      
      return {
        content: [
          {
            type: 'text',
            text: `找到 ${components.length} 个组件:\n\n${result}`,
          },
        ],
      };
    } catch (error) {
      perfMeasure.end(false, { error: error instanceof Error ? error.message : String(error) });
      await logMeasure.error(error instanceof Error ? error.message : String(error));
      throw error;
    }
  }

  private async handleGetDocumentation(params: GetDocumentationParams) {
    try {
      const docs = await this.documentSearcher.getComponentDocs(
        params.component,
        params.version,
        params.language
      );
      
      return {
        content: [
          {
            type: 'text',
            text: `${params.component} 组件文档:\n\n${docs}`,
          },
        ],
      };
    } catch (error) {
      throw error;
    }
  }

  private async handleListTemplates(params: any) {
    try {
      const templates = await this.templateEngine.getTemplatesByCategory(
        params.category,
        params.framework
      );
      
      const result = templates.map((template: TemplateInfo) => 
        `**${template.name}**\n${template.description}\n框架: ${template.framework}\n`
      ).join('\n');
      
      return {
        content: [
          {
            type: 'text',
            text: `可用模板:\n\n${result}`,
          },
        ],
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取热门组件
   */
  private async handleGetPopularComponents(params: any) {
    try {
      const limit = typeof params.limit === 'number' ? params.limit : 10;
      
      if (!this.componentRegistry.getPopularComponents) {
        throw new Error('Popular components feature not available');
      }
      
      const components = await this.componentRegistry.getPopularComponents(limit);
      
      const result = components.map((comp: ComponentInfo, index: number) => 
        `${index + 1}. **${comp.name}** (${comp.category})\n   ${comp.description}\n`
      ).join('\n');
      
      return {
        content: [
          {
            type: 'text',
            text: `热门组件 (前${limit}名):\n\n${result}`,
          },
        ],
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取服务器统计信息
   */
  private async handleGetServerStats() {
    try {
      const stats = await this.getServerStats();
      
      const result = `
📊 服务器统计信息
==================

🗄️  数据库状态: ${stats.database.status}
📦 组件总数: ${stats.componentStats.totalComponents}
🚀 缓存状态: ${stats.cache ? '启用' : '禁用'}
💾 运行模式: ${stats.mode}

📈 组件分类统计:
${stats.componentStats.categoryCounts.map(cat => `  - ${cat.category}: ${cat.count}个`).join('\n')}

🔥 热门组件:
${stats.componentStats.popularComponents.map((comp, i) => `  ${i + 1}. ${comp.name}`).join('\n')}

${stats.cache ? `
💾 缓存统计:
  - 内存缓存: ${stats.cache.memory.size}/${stats.cache.memory.maxSize} 项
  - Redis状态: ${stats.cache.redis.status}
  - 数据库缓存: ${stats.cache.database.totalItems} 项
` : ''}
      `.trim();
      
      return {
        content: [
          {
            type: 'text',
            text: result,
          },
        ],
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取健康状态
   */
  private async handleGetHealthStatus() {
    try {
      const health = await this.healthChecker.checkHealth();
      const report = this.healthChecker.generateHealthReport();
      
      return {
        content: [
          {
            type: 'text',
            text: report,
          },
        ],
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取性能监控报告
   */
  private async handleGetPerformanceReport(params: any) {
    try {
      let timeRange;
      
      if (params.timeRange) {
        const now = new Date();
        const timeMap: Record<string, number> = {
          '1h': 1,
          '24h': 24,
          '7d': 24 * 7,
        };
        const hours = timeMap[params.timeRange] || 24;
        
        timeRange = {
          from: new Date(now.getTime() - hours * 60 * 60 * 1000),
          to: now,
        };
      }
      
      const report = await this.performanceMonitor.generateReport(timeRange);
      
      return {
        content: [
          {
            type: 'text',
            text: report,
          },
        ],
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取服务器统计信息
   */
  async getServerStats() {
    try {
      const [dbHealth, componentStats, cacheStats] = await Promise.all([
        this.dbManager.healthCheck(),
        this.componentRegistry.getStats?.() || {
          totalComponents: 0,
          categoryCounts: [],
          popularComponents: [],
        },
        this.cacheManager?.getStats().catch(() => null) || null,
      ]);

      return {
        database: dbHealth.database,
        componentStats,
        cache: cacheStats,
        mode: this.componentRegistry.isDatabaseBacked?.() ? 'database' : 'memory',
      };
    } catch (error) {
      console.error('❌ Get server stats failed:', error);
      throw error;
    }
  }

  /**
   * 获取使用统计分析
   */
  private async handleGetUsageAnalytics(params: any) {
    try {
      let timeRange;
      
      if (params.timeRange) {
        const now = new Date();
        const timeMap: Record<string, number> = {
          '1h': 1,
          '24h': 24,
          '7d': 24 * 7,
          '30d': 24 * 30,
        };
        const hours = timeMap[params.timeRange] || 24;
        
        timeRange = {
          from: new Date(now.getTime() - hours * 60 * 60 * 1000),
          to: now,
        };
      }
      
      const analytics = await this.loggingService.getUsageAnalytics(timeRange);
      
      const result = `
📊 使用统计分析
==================

📊 总体统计:
  - 总调用次数: ${analytics.totalCalls.toLocaleString()}
  - 成功率: ${(analytics.successRate * 100).toFixed(1)}%
  - 平均响应时间: ${analytics.avgExecutionTime.toFixed(1)}ms

🔥 热门工具:
${analytics.topTools.map((tool, i) => `  ${i + 1}. ${tool.toolName}: ${tool.calls.toLocaleString()}次 (${(tool.successRate * 100).toFixed(1)}% 成功率)`).join('\n')}

📈 每日趋势:
${analytics.dailyStats.slice(0, 7).map(stat => `  ${stat.date}: ${stat.calls.toLocaleString()}次 (${(stat.successRate * 100).toFixed(1)}% 成功率)`).join('\n')}

${analytics.recentErrors.length > 0 ? `
❌ 最近错误:
${analytics.recentErrors.slice(0, 5).map(error => `  • ${error.toolName}: ${error.errorMessage.substring(0, 50)}... (${error.count}次)`).join('\n')}` : ''}
      `.trim();
      
      return {
        content: [
          {
            type: 'text',
            text: result,
          },
        ],
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取每日使用报告
   */
  private async handleGetDailyReport(params: any) {
    try {
      const date = params.date || new Date().toISOString().split('T')[0];
      const report = await this.loggingService.getDailyReport(date);
      
      const result = `
📅 ${report.date} 日使用报告
==================

📊 概要:
  - 总调用次数: ${report.summary.totalCalls.toLocaleString()}
  - 唯一会话数: ${report.summary.uniqueSessions.toLocaleString()}
  - 成功率: ${(report.summary.successRate * 100).toFixed(1)}%
  - 平均响应时间: ${report.summary.avgExecutionTime.toFixed(1)}ms

🔧 工具使用明细:
${report.toolBreakdown.map(tool => `  • ${tool.toolName}: ${tool.calls}次 (✅${tool.successCalls} ❌${tool.errorCalls} ⏰${tool.timeoutCalls}) - ${tool.avgExecutionTime.toFixed(1)}ms`).join('\n')}

📈 性能洞察:
  - 最慢工具: ${report.performanceInsights.slowestTool}
  - 最快工具: ${report.performanceInsights.fastestTool}
  - 最受欢迎: ${report.performanceInsights.mostUsedTool}
  ${report.performanceInsights.errorProneTools.length > 0 ? `- 错误频发: ${report.performanceInsights.errorProneTools.join(', ')}` : ''}
      `.trim();
      
      return {
        content: [
          {
            type: 'text',
            text: result,
          },
        ],
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取最近的调用日志
   */
  private async handleGetRecentLogs(params: any) {
    try {
      const limit = typeof params.limit === 'number' ? params.limit : 50;
      const toolName = typeof params.toolName === 'string' ? params.toolName : undefined;
      
      const logs = await this.loggingService.getRecentLogs(limit, toolName);
      
      if (logs.length === 0) {
        return {
          content: [
            {
              type: 'text',
              text: '📜 没有找到相关日志记录',
            },
          ],
        };
      }
      
      const result = `
📜 最近的调用日志 (${toolName ? `工具: ${toolName}` : '所有工具'})
==================

${logs.map(log => {
  const status = log.status === 'success' ? '✅' : log.status === 'error' ? '❌' : '⏰';
  const time = new Date(log.created_at!).toLocaleString('zh-CN');
  const executionTime = log.execution_time_ms;
  const sessionShort = log.session_id.substring(0, 8);
  
  let logLine = `${status} [${log.tool_name}] ${executionTime}ms - ${time} (${sessionShort})`;
  
  if (log.status === 'error' && log.error_message) {
    logLine += `\n   错误: ${log.error_message.substring(0, 100)}${log.error_message.length > 100 ? '...' : ''}`;
  }
  
  return logLine;
}).join('\n\n')}
      `.trim();
      
      return {
        content: [
          {
            type: 'text',
            text: result,
          },
        ],
      };
    } catch (error) {
      throw error;
    }
  }

  async run(): Promise<void> {
    try {
      // 确保服务器已初始化
      if (!this.initialized) {
        await this.initialize();
      }

      const transport = new StdioServerTransport();
      await this.server.connect(transport);
      console.error('🚀 MCP Ant Design Database Server running on stdio');
    } catch (error) {
      console.error('❌ Failed to start server:', error);
      throw error;
    }
  }

  /**
   * 优雅关闭服务器
   */
  async shutdown(): Promise<void> {
    try {
      console.log('🛑 Shutting down MCP Server...');
      
      // 清理监控系统
      if (this.performanceMonitor) {
        this.performanceMonitor.cleanup();
      }
      
      if (this.healthChecker) {
        this.healthChecker.cleanup();
      }
      
      // 清理日志系统
      if (this.loggingService) {
        this.loggingService.cleanup();
      }
      
      await this.dbManager.close();
      
      if (this.cacheManager) {
        this.cacheManager.destroy();
      }
      
      await RedisClient.disconnect();
      
      console.log('✅ MCP Server shutdown completed');
    } catch (error) {
      console.error('❌ Error during shutdown:', error);
    }
  }

  // 参数验证方法（与原有版本相同）
  private validateGenerateCodeParams(args: unknown): GenerateCodeParams {
    if (!args || typeof args !== 'object') {
      throw new Error('Invalid arguments: expected object');
    }
    
    const params = args as Record<string, unknown>;
    
    if (!params.component || typeof params.component !== 'string') {
      throw new Error('Missing required parameter: component');
    }
    
    return {
      component: params.component,
      props: (params.props as Record<string, any>) || {},
      template: typeof params.template === 'string' ? params.template : undefined,
      framework: ['react', 'vue', 'angular'].includes(params.framework as string) 
        ? (params.framework as 'react' | 'vue' | 'angular') 
        : 'react',
      includeImports: typeof params.includeImports === 'boolean' ? params.includeImports : true,
      includeStyles: typeof params.includeStyles === 'boolean' ? params.includeStyles : false,
    };
  }

  private validateSearchComponentsParams(args: unknown): SearchComponentsParams {
    if (!args || typeof args !== 'object') {
      throw new Error('Invalid arguments: expected object');
    }
    
    const params = args as Record<string, unknown>;
    
    if (!params.query || typeof params.query !== 'string') {
      throw new Error('Missing required parameter: query');
    }
    
    return {
      query: params.query,
      category: typeof params.category === 'string' ? params.category : undefined,
      limit: typeof params.limit === 'number' ? params.limit : 10,
    };
  }

  private validateGetDocumentationParams(args: unknown): GetDocumentationParams {
    if (!args || typeof args !== 'object') {
      throw new Error('Invalid arguments: expected object');
    }
    
    const params = args as Record<string, unknown>;
    
    if (!params.component || typeof params.component !== 'string') {
      throw new Error('Missing required parameter: component');
    }
    
    return {
      component: params.component,
      version: typeof params.version === 'string' ? params.version : undefined,
      language: ['zh', 'en'].includes(params.language as string) 
        ? (params.language as 'zh' | 'en') 
        : 'zh',
    };
  }
}